#coding=utf-8

'''
Created on 2011-8-30

@author: chris
'''
import traceback
import urllib2
import sys
import time
import os
from ripper.core.Exceptions import DownloadException
from urllib import urlretrieve
import uuid

class DownloadHandler(object):
    '''
            下载文件
    '''
    
    def __init__(self, baseDir):
        '''
        Constructor
        '''
        self.baseDir = baseDir # 下载到的文件夹
        
    # 下载
    def download(self, uri, fileName=None, retry=15):
        try:
            self.__download(uri, fileName)
        except Exception:
            traceback.print_exc(file=sys.stdout)
            print 'download error ', uri
            if retry > 0:
                print 'retry'
                time.sleep(26-retry)
                return self.download(uri, fileName, retry-1)
            else :
                print 'file already retry %d times, game over.' % retry
                raise DownloadException(u'Download failed:' + fileName)
        finally:
            pass
        
            
    def __download(self, uri, fname=None, gheaders=None):
        print 'downloading ', uri
        if fname == None:
            filename, header = urlretrieve(uri)
            print  'downloaded', uri
            return filename
        req = None
        if gheaders != None:
            req = urllib2.Request(url=uri, headers=gheaders)
        else:
            req = urllib2.Request(uri)
        r = urllib2.urlopen(req)
        fp = open(os.path.join(self.baseDir, fname), 'wb')
        fp.write(r.read())
        fp.close()
        return fname
    
# 生成UUID, 命名图片和文本文件
def getId():
    id0 = str(hex(int(str(time.time()).replace('.',''))))
    id1 = str(uuid.uuid1())
    return id0+'-'+id1
    
if __name__ == '__main__':
    uri = 'http://www.tabletennisdb.com/assets/table-tennis-images/blades/adidas-c300-off.jpg'
    dd = DownloadHandler('h:/resource')
    dd.download(uri)